package com.zwt.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

public class TString {

	public static String formatDecimal(Object data,String format) {
		if(StringUtils.isEmpty(format)) {
            format = "#,###";
        }
		DecimalFormat df = new DecimalFormat(format); 
		String result = "0";
		String unit="";
		if(null!=data){
			if("#.0".equals(format)){
				Double num = Double.parseDouble(data.toString());
				if(num>100000){
					num=num/10000;
					unit="万";
					result = df.format(num);
				}else{
					result = num+"";
				}
			}else{
				Long num = Long.parseLong(data.toString());
				if(num>100000){
					num=num/10000;
					unit="万";
				}
				result = df.format(num);
			}
		}
		return result+unit;
	}
	
	public static long getCRC32(String value) {
		Checksum checksum = new CRC32();
		        byte[] bytes = value.getBytes();
		        checksum.update(bytes, 0, bytes.length);
		        return checksum.getValue();
	}
    /**
     * @param target   12345678,1234567@qq.com
     * @param format
     * @return  1234****
				123****@qq.com
     */
    public static String blurString(String target,String format) {
    	if(!StringUtils.isNotEmpty(format)) {
            format = "*";
        }
    	String end="";
    	String start=target;
    	if(target.indexOf("@")>-1){
    		String[] mailArr = target.split("[@]");
    		start=mailArr[0];
    		end="@"+mailArr[1];
    	}
    	int blurIndex = (int) (start.length()/2.0+0.5);
    	if(start.length()%2!=0) {
            start = start.substring(0, blurIndex - 1);
        } else {
            start = start.substring(0, blurIndex);
        }
    	for(int i=0;i<blurIndex;i++){
    		start+=format;
    	}
        return start+end;
    }
    
    /**前三位，后四位保留。其余 *
     * @param target 目标字符串
     * @param format   替换字符串
     * @param headNum   头部保留几个
     * @param endNum  结尾保留几个
     * @return
     */
    public static String blurCardString(String target,String format,int headNum,int endNum){
    	if(!StringUtils.isNotEmpty(format)) {
            format = "*";
        }
    	String start="";
    	if(StringUtils.isEmpty(target)||target.length()<=headNum+endNum){
    		return target;
    	}else{
    		start = target.substring(0, headNum);
    	}
    	for(int i=0;i<target.length()-headNum-endNum;i++){
    		start+=format;
    	}
        return start+=target.substring(target.length()-endNum, target.length());
    }

	/**
	 * @param num 待补齐数字
	 * @param size  补齐位数
	 * @return
	 */
	public static String getCompleteStr(Object num,int size) {
		StringBuilder str2 = new StringBuilder(""+num);
		while(str2.length()<size){
			str2.insert(0, "0");
		}
		return str2.toString();
	}

    /**
     * 字符串补0
     *
     * @param str
     * @param strLength
     * @return
     */
    public static String addZeroForNum(String str, int strLength) {
        int strLen = str.length();
        StringBuffer sb = null;
        while (strLen < strLength) {
            sb = new StringBuffer();
            // sb.append("0").append(str);// 左补0
            sb.append(str).append("0");//右补0
            str = sb.toString();
            strLen = str.length();
        }
        return str;
    }

	/**
	 * 校验特殊字符
	 * @param string
	 * @return
	 */
	public static boolean isConSpeCharacters(String string) {
		if (string.replaceAll("[\u4e00-\u9fa5]*[a-z]*[A-Z]*\\d*-*_*\\s*", "").length() == 0) {
			//如果不包含特殊字符
			return false;
		}
		return true;
	}

    public static void main(String[] as){

    }
    /**
     * 
     * @param bankCard 格式化字符串
     * @param index 断位
     * @param str 断位符号
     * @return
     */
    public static String bankCardFormart(String bankCard,int index,String str){
    	char[] stringArr = bankCard.toCharArray();
    	String card = "";
    	int mod = 1;
    	int strSize = stringArr.length;
    	for(int i=strSize-1;i>=0;i--,mod++){
    		card = stringArr[i] + card;
    		if( mod%index==0 && mod<strSize ){
    			card = str + card;
    		}
    	}
    	return card;
    }


	/**
	 * 
	 * @param number 
	 * @param flo 保留小数位数
	 * @param fix 减少数值
	 * @return
	 */
    public static String formatDecimals(Object number,String flo,Integer fix) {
    	int ns  = 2;
		if(number==null && !StringUtils.isEmpty(flo) && "0".equals(flo)){
			return "0";
		}
    	if(number==null){
    		return "0.00";
		}
     	if(flo!=null){
    		try{
    			ns = Integer.parseInt(flo);
    		}catch(NumberFormatException e){
    			ns = 2;
    		}
    	} 
     	String dou = "";
     	if(fix!=null&&fix>0){
     		dou = Double.parseDouble(number.toString())/fix + "";
     	}else{
     		dou = number + "";
     	}
        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(ns);
//      如果不需要四舍五入，可以使用RoundingMode.DOWN
//      nf.setRoundingMode(RoundingMode.DOWN);
//        nf.setRoundingMode(RoundingMode.UP);
        String str = nf.format(Double.parseDouble(dou));
        if(0==ns){//0 不许保留小数。
        	return str;
        }
        if(str.indexOf(".")>-1){
        	String util = str.substring(str.indexOf("."), str.length());
        	if(util.length()>ns){
        		return str;
        	}
        	return str + 0;
        }else if(1==ns){
			return str + ".0";
		}else{
        	return str + ".00";
        }
    }

	/**
	 * 将json数组字符串转换为字符串
	 * @param jsonStr
	 * @return
	 */
	public static String jsonArrayParseString(String jsonStr){
		if (jsonStr == null || jsonStr.trim().length() <= 0) {
            return "";
        }
		StringBuffer sb = new StringBuffer();
		try{
			JSONArray array = JSONArray.parseArray(jsonStr);
			for (int i = 0; i < array.size(); i++) {
				if ((i + 1) != array.size()) {
					sb.append(array.get(i).toString() + "/");
				} else {
					sb.append(array.get(i).toString());
				}
			}
		}catch (Exception e) {
			return "";
		}
		return sb.toString();
	}

	/**
	 * html 编码
	 * @param source
	 * @return
	 */
	public static String htmlEncode(String source) {
		if (source == null) {
			return "";
		}
		StringBuffer buffer = new StringBuffer();
		for (int i = 0; i < source.length(); i++) {
			char c = source.charAt(i);
			switch (c) {
				case '<':
					buffer.append("&lt;");
					break;
				case '>':
					buffer.append("&gt;");
					break;
				case '&':
					buffer.append("&amp;");
					break;
				/*case '"':
					buffer.append("&quot;");
					break;*/
				case 10:
				case 13:
					break;
				default:
					buffer.append(c);
			}
		}
		return buffer.toString();

	}


	/**
	 * 获取1~100位随机验证码
	 * @author Autorun
	 * @param count 生成验证码位数
	 * @return
	 */
	public static String getRandom(Integer count) {
		if (count == null || count <= 0 || count > 100) {
            count = 6;
        }
		String num = "";
		for (int i = 0 ; i < count ; i ++) {
			num = num + String.valueOf((int) Math.floor(Math.random() * 9 + 1));
		}
		return num;
	}

	public static Integer getInteger(Object o){
		if(o == null){
			return 0;
		}
		String n = o.toString();
		if( n.indexOf(".") > -1 ){
			n = n.substring(0,n.indexOf("."));
		}
		return Integer.parseInt(n);
	}


	/**
	 * 检查名字中是否包含指定字符串
	 * @param sourceName (需要检测的字符串)
	 * @param names (被检测的字符串)
	 * @return
	 */
	public static boolean isIncludeName(String sourceName, String[] names){
		if (org.springframework.util.StringUtils.isEmpty(sourceName) ||
				names == null || names.length == 0) {
            return false;
        }
		for (String name : names) {
			if (org.springframework.util.StringUtils.isEmpty(name)) {
                continue;
            }
			if (sourceName.indexOf(name) != -1) {
                return true;
            }
		}
		return false;
	}

	/**
	 * 将double数字格式化为指定小数位数的string,不足位数0自动补全
	 * 如:15 指定小数位2位 格式化之后:15.00
	 * @param v 需要格式化的数字
	 * @param scale 小数点后保留多少位
	 * @return
	 */
	public static String roundByScale(double v, int scale) {
		if (scale < 0) {
			throw new IllegalArgumentException(
					"The scale must be a positive integer or zero");
		}
		if(scale == 0){
			return new DecimalFormat("0").format(v);
		}
		String formatStr = "0.";
		for(int i=0;i<scale;i++){
			formatStr = formatStr + "0";
		}
		return new DecimalFormat(formatStr).format(v);
	}

	/**
	 * 将字符串格式化,每隔4位加一个空格
	 * @param card
	 * @return
	 */
	public static String strFormat(String card){
		StringBuilder str = new StringBuilder(card.replace(" ",""));
		int i = str.length() / 4;
		int j = str.length() % 4;
		for (int x = (j == 0 ? i - 1 : i); x > 0; x--) {
			str = str.insert(x * 4," ");
		}
		return str.toString();
	}


	private static boolean isStringEmpty(Object str) {
		return (str == null || "".equals(str));
	}

	public static boolean isEmpty(Object str) {
		return isStringEmpty(str);
	}

	public static boolean isNotEmpty(Object str) {
		return !isStringEmpty(str);
	}
	/**
	 * 字符串截取替换
	 * @param str		原始字符串
	 * @param targetLong		保留长度，如果不传，返回原始字符串。
	 * @param targetStr			超过保留长度之后的替换，如果不传，以省略号结尾。
	 * @return
	 */
	public static String strCutReplace(String str,Integer targetLong,String targetStr){
		String resultStr = "";
		if(StringUtils.isNotEmpty(str)) {
			if(targetLong!=null && targetLong>0) {
				if(str.length()>targetLong) {
					resultStr = str.substring(0,targetLong) + (StringUtils.isNotEmpty(targetStr) ? targetStr : "...");
				}else {
					resultStr = str;
				}
			}else {
				resultStr = str;
			}
		}
		return resultStr;
	}

	public static String splitNum(Object strNum){
		if (strNum != null){
			String str = strNum.toString();
			return str.substring(0,str.indexOf("."));
		}
		return null;
	}
	
	/**
	 * 删除Html标签
	 * 
	 * @param inputString
	 * @return
	 */
	public static String htmlRemoveTag(String inputString) {
		if (inputString == null)
			return null;
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		Pattern p_script;
		Matcher m_script;
		Pattern p_style;
		Matcher m_style;
		Pattern p_html;
		Matcher m_html;
		try {
			// 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>";
			// 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>";
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
			String nbsp_rgx="\\&nbsp;";
			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签
			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签
			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签
			Pattern nbsp_html = Pattern.compile(nbsp_rgx);
			Matcher m_nbsp = nbsp_html.matcher(htmlStr);
			htmlStr=m_nbsp.replaceAll("");
			textStr = htmlStr;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return textStr.trim();// 返回文本字符串
	}

	/**
	 * 将对象转为字符串
	 * @param obj
	 * @return
	 */
	public static String valueOf(Object obj){
		return "null".equals(String.valueOf(obj)) ?
				"" : JSONObject.toJSONString(obj).toString();
	}
}
